package o2o.web.actions.shop;


//店铺通用方法

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.agent.UserAgentRelationMemory;
import o2o.cache.area.RegionInfoMemory;
import o2o.cache.shop.*;
import o2o.cache.user.UserInfoMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.agent.ShopAgentRelation;
import o2o.dao.PO.area.RegionInfo;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.shop.*;
import o2o.dao.PO.square.SquareVerifyInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.area.RegionInfoVO;
import o2o.dao.VO.shop.ShopImageTypeVO;
import o2o.dao.VO.shop.ShopImagesVO;
import o2o.dao.VO.shop.ShopTypeInfoVO;
import o2o.service.shop.ShopService;
import o2o.company.model.ShopInfo;
import o2o.system.data.SYS_SETTINGS;
import o2o.utils.CommonUtils;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class ShopMan {
    //获取店铺实景
    public static List<ShopImageTypeVO> getShopImages(Long shopId) {

        List<ShopImageType> list = ShopImageTypeMemory.getInstance().listOfShop(shopId);
        if (ValidateUtil.isAbsList(list)) {
            List<ShopImageTypeVO> rList = new ArrayList<ShopImageTypeVO>();
            for (int i = 0; i < list.size(); i++) {//该店的所有类别
                if (null != list.get(i)) {//某一类下的
                    ShopImageTypeVO typeVo = new ShopImageTypeVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(list.get(i), typeVo, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }

                    List<ShopImagesVO> iList = new ArrayList<ShopImagesVO>();
                    if (ValidateUtil.isAbsList(list.get(i).getImages())) {
                        for (int j = 0; j < list.get(i).getImages().size(); j++) {//该类别下的图片
                            if (null != list.get(i).getImages().get(j)) {//图片信息
                                ShopImagesVO v = new ShopImagesVO();
                                try {
                                    ObjectUtils.copyPropertiesExclude(list.get(i).getImages().get(j), v, null);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    continue;
                                }
                                if (null != v) {
                                    iList.add(v);
                                }
                            }
                        }
                        typeVo.setImages(iList);
                    }


                    if (null != typeVo) {
                        rList.add(typeVo);
                    }
                }
            }
            if (ValidateUtil.isAbsList(rList)) {
                return rList;
            }
        }

        return null;
    }


    public static ResultInfo addShop(String createUser, ShopInfoDB info, String shopType, String regions,
                                     String idCardNumber// 店主身份证号

    ) {
        return addShop(createUser, info, shopType, regions, idCardNumber, null);
    }

    //添加店铺
    public static ResultInfo addShop(String createUser, ShopInfoDB info, String shopType, String regions,
                                     String idCardNumber// 店主身份证号
            , Integer shopTag
    ) {
        info.setCreateUser(createUser);
        long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        info.setDelFlag(0);
        info.setIsOpen(1);
        // cswm yangtk 2019年8月31日10:22:20
        info.setCityAdmin(getShopBelongCityAdmin(createUser, info.getCityAdmin())); // 添加店铺所属代理
        boolean isExactUserType = User.isExactUserType(); // 多权限

        //判断店主是否存在
        UserInfo userInfo = User.getUserInfoByUsername(info.getOwnUsername());
        if (null == userInfo) { //账号不存在
            //添加账号
            try {
                String psw = "123456";
                if (null != SYS_SETTINGS.SHOP_DEFAULT_PSW && 0 == 1 - SYS_SETTINGS.SHOP_DEFAULT_PSW && info.getOwnUsername() != null && info.getOwnUsername().length() >= 6) {
                    // 账号>=6位 且 店铺密码使用账号后6位
                    psw = info.getOwnUsername().substring(info.getOwnUsername().length() - 6);
                }
                String realUsername = User.getUniqueUserName(info.getOwnUsername());
                String phone = info.getOwnUsername();
                info.setOwnUsername(realUsername);
                User.getInstance().addUser(realUsername, phone, psw, UserType.SHOP_OWNER, idCardNumber);
            } catch (Exception e) {
                e.printStackTrace();
                return new ResultInfo(e.getMessage());
            }
            //将店主账号姓名、头像  设置为店铺信息
//            User.getInstance().modifyUserBaseInfo(info.getOwnUsername(), info.getOwnName(), info.getImageUrl(), "");
        } else {//有这个账号，看这个用户的类型
            info.setOwnUsername(userInfo.getUsername());
            switch (userInfo.getUserType()) {
                case UserType.SHOP_OWNER: {//如果已经是店主了  那不允许再添加账号
                    List<ShopInfo> shopInfo = ShopMemory.getInstance().getShopListByUserName(userInfo.getUsername());
                    if (null != shopInfo && shopInfo.size() > 0) {
//                        return AjaxResult.errorResult("当前店主账号已存在，不允许再添加新店铺");
                        return new ResultInfo("当前店主账号已存在，不允许再添加新店铺");
                    }
                }
                break;
                case UserType.USER: {//普通用的话，升级为店主
                    User.getInstance().modifyUserType(userInfo.getUsername(), UserType.SHOP_OWNER);
                    userInfo.setUserType(UserType.SHOP_OWNER);
                }
                break;
                case UserType.POSTMAN: {//配送员的话也不允许
//                    return AjaxResult.errorResult("当前店主账号是配送员，请更换店主账号");
                    if (isExactUserType) {
                        // 骑手也能成为店铺

                    } else {
                        return new ResultInfo("当前店主账号是配送员，请更换店主账号");
                    }
//                    return new ResultInfo("当前店主账号是配送员，请更换店主账号");
                }
//                break;
                case UserType.ADMIN: {//管理员的话看看他有没有店铺
                    List<ShopInfo> shopInfo = ShopMemory.getInstance().getShopListByUserName(userInfo.getUsername());
                    if (null != shopInfo && shopInfo.size() > 0) {
//                        return AjaxResult.errorResult("当前店主账号已存在，不允许再添加新店铺");
                        return new ResultInfo("当前店主账号已存在，不允许再添加新店铺");

                    }
                }
                break;
            }

            // 修改用户的身份证号
            User.modifyUserIdCardNumber(userInfo.getUsername(), idCardNumber, createUser);
        }


        String geocode = Geohash.encode(info.getLat(), info.getLng());
        Long areaPoint = Geohash.getArea(info.getLat(), info.getLng());
        info.setGeocode(geocode);
        info.setAreaPoint(areaPoint);


        if (null != SYS_SETTINGS.SHOP_DEFAULT_STAR) {
            info.setStar(SYS_SETTINGS.SHOP_DEFAULT_STAR);
            info.setScore(Double.parseDouble(SYS_SETTINGS.SHOP_DEFAULT_STAR + ""));
        }

        // 是否配送
        if (null == info.getIsPeiSong()) {
            if (null != SYS_SETTINGS.SHOP_VERFY_ISPEISONG) {
                info.setIsPeiSong(SYS_SETTINGS.SHOP_VERFY_ISPEISONG);
            } else {
                info.setIsPeiSong(1);
            }
        }
        // 是否到店
        if (null == info.getIsDaoDian()) {
            if (null != SYS_SETTINGS.SHOP_VERFY_ISDAODIAN) {
                info.setIsDaoDian(SYS_SETTINGS.SHOP_VERFY_ISDAODIAN);
            } else {
                info.setIsDaoDian(0);
            }
        }
        // 配送方式
        if (null == info.getIsSelfPost()) {
            if (null != SYS_SETTINGS.SHOP_VERFY_ISSELFPOST) {
                info.setIsSelfPost(SYS_SETTINGS.SHOP_VERFY_ISSELFPOST);
            } else {
                info.setIsSelfPost(0);
            }
        }

        //  支持货到付款？？ yangtk
        if (null == info.getIsCashOnDelivery()) {
            if (null != SYS_SETTINGS.IS_CASH_ON_DELIVERY) {
                info.setIsCashOnDelivery(SYS_SETTINGS.IS_CASH_ON_DELIVERY);
            } else {
                info.setIsCashOnDelivery(0);
            }
        }

        //初始餐具费用
        if (null == info.getHasCanJu()) {
            info.setHasCanJu(0);
            info.setCanJuPrice(0d);
        }

        //转成英文城市名称
        if (ValidateUtil.isNotNull(info.getCity())) {
            info.setCityEN(JYPinyinHelper.toHanyuPinyin(info.getCity()));
        }

        ShopInfoDB shopInfoDB = new ShopInfoDB();
        try {
            ObjectUtils.copyPropertiesExclude(info, shopInfoDB, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("新增失败，请稍后再试.");
        }

        //店铺信息保存到数据库
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.ShopInfo, shopInfoDB);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("新增失败，请稍后再试");
        }


        //店铺信息添加缓存
        Long shopId = ShopMemory.getInstance().add(time);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_ADD).setLong01(time);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        if (null == userInfo) {//账号不存在
            //将店主账号姓名、头像  设置为店铺信息
            User.getInstance().modifyUserBaseInfo(info.getOwnUsername(), info.getOwnName(), info.getImageUrl(), "", null);
        }

        //
        // //店铺行业关联
        // if (ValidateUtil.isNotNull(shopType)) {
        //     String[] typs = shopType.split(",");
        //     if (null != typs & typs.length > 0) {
        //         for (int i = 0; i < typs.length; i++) {
        //
        //             try {
        //                 ShopTypeRelation shopTypeRelation = new ShopTypeRelation();
        //                 shopTypeRelation.setShopId(shopId);
        //                 shopTypeRelation.setShopTypeId(Integer.parseInt(typs[i]));
        //
        //                 shopTypeRelation.setCreateTime(time);
        //                 shopTypeRelation.setCreateUser(createUser);
        //                 shopTypeRelation.setDelFlag(0);
        //                 shopTypeRelation.setOrderNo(0);
        //
        //                 try {
        //                     UserDaoSql.getInstance().insertObj(PojoTables.ShopTypeRelation, shopTypeRelation);
        //                 } catch (SQLException e) {
        //                     e.printStackTrace();
        //                     return new ResultInfo("店铺关联行业失败，请稍后再试");
        //                 }
        //             } catch (Exception e) {
        //                 e.printStackTrace();
        //                 continue;
        //             }
        //
        //         }
        //
        //         // 店铺关联行业添加缓存
        //         ShopTypeRelationMemory.getInstance().add(shopId);
        //         try {
        //             JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_TYPE_RELATION_ADD).setLong01(shopId);
        //             JmsSender.setTopicSender(notify);
        //         } catch (Exception e) {
        //         }
        //     }
        // }
        // 处理行业
        ResultInfo typeResult = ShopMan.dealShopTypes(shopId, false, shopType, createUser);
        if (null == typeResult) {
            return new ResultInfo("处理店铺行业失败,请稍后重试");
        } else {
            if (!typeResult.isSuccess()) {
                return typeResult;
            }
        }
        //店铺关联商圈
        if (ValidateUtil.isNotNull(regions)) {
            String[] regs = regions.split(",");
            if (null != regs & regs.length > 0) {
                for (int i = 0; i < regs.length; i++) {
                    try {
                        ShopRegionRelation shopRegionRelation = new ShopRegionRelation();
                        shopRegionRelation.setShopId(shopId);
                        shopRegionRelation.setShopOwnUsername(info.getOwnUsername());
                        shopRegionRelation.setRegionId(Long.parseLong(regs[i]));
                        shopRegionRelation.setProvince(info.getProvince());
                        shopRegionRelation.setCity(info.getCity());
                        shopRegionRelation.setCounty(info.getCounty());
                        shopRegionRelation.setRegion(info.getRegion());


                        shopRegionRelation.setCreateTime(time);
                        shopRegionRelation.setCreateUser(createUser);
                        shopRegionRelation.setDelFlag(0);

                        try {
                            UserDaoSql.getInstance().insertObj(PojoTables.SHOP_REGION_RELATION, shopRegionRelation);
                        } catch (SQLException e) {
                            e.printStackTrace();
                            return new ResultInfo("店铺关联商圈失败，请稍后再试");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }

                }

                //店铺关联行业添加缓存
                ShopRegionRelationMemory.getInstance().add(shopId);

            }
        }

        //添加店铺额外信息
//        addShopExtraInfo(shopId, info.getOwnUsername(), createUser, 0);
        addShopExtraInfo(shopId, info.getOwnUsername(), createUser, 0, shopTag);

        // 哒哒对接 -自动注册门店
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        ShopService.getInstance().registerOrUpdateDeliverShop(null, shopInfo, true);
        return new ResultInfo("", shopId);
    }


    // 创建默认的创业商圈的关联店铺
    public static Long createSquareShop(SquareVerifyInfo info, String opUser, Long cTime, Connection cn) throws Exception {
        ShopInfoDB db = new ShopInfoDB();

        db.setShopName(info.getSquareName()).setTelephone(info.getPhone())
                .setAddress(info.getAddress())
                // .setDescs(info.getNote())
                .setShopCategory(info.getSquareCategory())
                .setImageUrl(info.getImageUrl())
                .setAffiche(info.getAffiche())
                .setLat(info.getLat()).setLng(info.getLng())
                .setProvince(info.getProvince())
                .setCity(info.getCity())
                .setCounty(info.getCounty())
                .setDelFlag(0)
                .setScore(0.0d)
                .setOwnUsername(info.getUsername())
                .setCreateUser(opUser)
                .setPacketPrice(0.0d).setIsPeiSong(1).setIsDaoDian(0).setIsOpen(1).setOrderNo(0L).setStar(5)
                .setCloudShopType(CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_SQUARE)
                .setCreateTime(cTime);
        Long shopId = null;
        if (cn == null) {
            shopId = UserDaoSql.getInstance().saveObj(PojoTables.ShopInfo, db);
            ShopMemory.getInstance().add(cTime);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_ADD).setLong01(cTime);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        } else {
            shopId = UserDaoSql.getInstance().saveObj(PojoTables.ShopInfo, db, cn);
        }
        // 添加额外信息
        ShopInfoExtra extra = new ShopInfoExtra();
        extra.setCreateTime(cTime).setDelFlag(0)
                .setShopId(shopId);
        Integer star = 5;
        Double score = 5.0d;
        if (null != SYS_SETTINGS.SHOP_DEFAULT_STAR) {
            star = SYS_SETTINGS.SHOP_DEFAULT_STAR;
            score = Double.parseDouble(SYS_SETTINGS.SHOP_DEFAULT_STAR + "");
        }
        extra.setStar(star).setScore(score);
        extra.setBuzzLicImageUrl(info.getLicenceImageUrl())
                .setIDCardHImageUrl(info.getImageUrl1())
                .setIDCardAImageUrl(info.getImageUrl2())
                .setIDCardBImageUrl(info.getImageUrl3());
        addShopExtraInfo(extra, cn);
        return shopId;
    }

    // 获取商家所属的代理
    public static String getShopBelongCityAdmin(String username, String cityAdmin) {
        if (!StringUtils.isEmpty(cityAdmin)) {
            return cityAdmin;
        }
        if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
            UserInfo user = UserInfoMemory.getInstance().getUserInfo(username);
            if (user == null) {
                return null;
            }
            if (user.getUserType() == UserType.ADMIN) {
                return user.getUsername();
            }

        }
        return null;
    }

    //添加店铺关联的商圈
    public static ResultInfo addShopRegionRelation(Long shopId, String regions, String createUser) {
        if (ValidateUtil.isNotID(shopId)) {
            return new ResultInfo("关联店铺ID不能为空");
        }
        StringBuilder sbType = new StringBuilder();
        sbType.append("delete from ").append(PojoTables.SHOP_REGION_RELATION).append(" where shopId = ").append(shopId);
        try {
            UserDaoSql.getInstance().executeBySql(sbType.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("删除店铺关联商圈失败，请稍后再试");
        }

        if (ValidateUtil.isNull(regions)) {
            return new ResultInfo();
        }
        //店铺关联商圈
        if (ValidateUtil.isNotNull(regions)) {
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
            if (null == shopInfo) {
                return new ResultInfo("");
            }
            String[] regs = regions.split(",");
            if (null != regs & regs.length > 0) {
                Long time = DateUtils.getCurrTime();
                for (int i = 0; i < regs.length; i++) {

                    try {
                        ShopRegionRelation shopRegionRelation = new ShopRegionRelation();
                        shopRegionRelation.setShopId(shopId);
                        shopRegionRelation.setShopOwnUsername(shopInfo.getOwnUsername());
                        shopRegionRelation.setRegionId(Long.parseLong(regs[i]));
                        shopRegionRelation.setProvince(shopInfo.getProvince());
                        shopRegionRelation.setCity(shopInfo.getCity());
                        shopRegionRelation.setCounty(shopInfo.getCounty());
                        shopRegionRelation.setRegion(shopInfo.getRegion());


                        shopRegionRelation.setCreateTime(time);
                        shopRegionRelation.setCreateUser(createUser);
                        shopRegionRelation.setDelFlag(0);

                        try {
                            UserDaoSql.getInstance().insertObj(PojoTables.SHOP_REGION_RELATION, shopRegionRelation);
                        } catch (SQLException e) {
                            e.printStackTrace();
                            return new ResultInfo("店铺关联商圈失败，请稍后再试");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }

                }

                //店铺关联行业添加缓存
                ShopRegionRelationMemory.getInstance().reloadByShop(shopId);

            }
        }

        return new ResultInfo();
    }


    //删除店铺
    public static ResultInfo deleteShop(String shopIds, String opUsername, int updateUserType) {
        if (ValidateUtil.isNull(shopIds)) {
            return new ResultInfo("请选择要删除的店铺");
        }

        if (SYS_SETTINGS.HAS_ORDER_REFUSE_DEL_SHOP_POSTMAN != null && SYS_SETTINGS.HAS_ORDER_REFUSE_DEL_SHOP_POSTMAN == 1 && shopHasOrder(shopIds)) {
            return new ResultInfo("当前商家有订单无法删除");
        }

        String[] shopIdArr;
        if (shopIds.indexOf(",") > -1) {
            // 传入的是多个Id
            shopIdArr = shopIds.split(",");
        } else {
            // 传入的是单个Id
            shopIdArr = new String[1];
            shopIdArr[0] = shopIds;
        }

        HashSet<String> userSet = new HashSet<>();
        if (null != shopIdArr && shopIdArr.length > 0) {
            for (int i = 0; i < shopIdArr.length; i++) {
                if (ValidateUtil.isNull(shopIdArr[i])) {
                    continue;
                }
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(Long.parseLong(shopIdArr[i]));
                if (null == shopInfo) {
                    return new ResultInfo("当前店铺不存在请查证");
                }

                if (User.notHasCityAuth(opUsername, shopInfo.getCity(), updateUserType)) {
                    return new ResultInfo("您没有访问该城市数据的权限");
                }

                userSet.add(shopInfo.getOwnUsername());
            }
        }


        //数据库删除
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set delFlag=1,updateUser = '").append(opUsername)
                .append("' where id in(").append(shopIds).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("删除店铺失败，请稍后再试");
        }
        Set<Long> shopIdSet = new HashSet<>();
        try {
            shopIdSet = CommonUtils.splitToSet(shopIds, Long.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //删除店铺缓存
        if (null != shopIdArr && shopIdArr.length > 0) {
            for (int i = 0; i < shopIdArr.length; i++) {
                if (ValidateUtil.isNull(shopIdArr[i])) {
                    continue;
                }
                try {
                    ShopMemory.getInstance().delete(Long.parseLong(shopIdArr[i]));
                    try {
                        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_DELETE).setLong01(Long.parseLong(shopIdArr[i]));
                        JmsSender.setTopicSender(notify);
                    } catch (Exception e) {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //删除行业
            deleteShopTypes(shopIds, shopIdArr, opUsername);

        }

        // 恢复商家的用户身份
        if (null != userSet && userSet.size() > 0) {
            for (String username : userSet) {
                if (ValidateUtil.isNull(username)) {
                    // 删除店铺，恢复用户其他身份
                    continue;
                }
                User.delRevertUser(username);
            }
        }
        return new ResultInfo();
    }

    // 删除商家验证商家是否有订单
    private static boolean shopHasOrder(String shopIds) {
        Set<Long> splitToSet = CommonUtils.splitToSet(shopIds, Long.class);
        if (splitToSet == null || splitToSet.isEmpty()) {
            return false;
        }
        List<ShopInfo> list = new ArrayList<>();
        splitToSet.forEach(item -> {
            ShopInfo shop = ShopMemory.getInstance().getShopById(item);
            if (shop != null) {
                list.add(shop);
            }
        });
        Set<String> usernameSet = list.stream().map(item -> "'" + item.getOwnUsername() + "'").collect(Collectors.toSet());
        StringBuilder sql = new StringBuilder();
        sql.append(" select count(1) as counts from ").append(PojoTables.OrderInfo)
                .append(" as OI WHERE OI.delFlag = 0 and (").append("OI.shopId in (").append(StringUtils.join(splitToSet, ",")).append(") ")
                .append(" or ( OI.isShopPaoTuiOrder = 1 and OI.username in (").append(StringUtils.join(usernameSet, ",")).append(")").append(")")
                .append(") ");
        long count = 0;
        try {
            count = UserDaoSql.getInstance().getCount(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ValidateUtil.isAbsLong(count);
    }


    //根据商圈获取店铺列表
    public static List<ShopInfo> listOfAgentId(Long agentId, String content) {
        return listOfAgentId(agentId, null, null, content, false, null, null, ShopCategoryMan.shopTypeShopping, false, false);
    }

    public static List<ShopInfo> listOfAgentId(Long agentId, Integer isSeriesSale) {
        return listOfAgentId(agentId, null, null, null, false, null, isSeriesSale, ShopCategoryMan.shopTypeShopping, false, false);
    }

    public static List<ShopInfo> listOfAgentId(Long agentId, Integer typeId, Long shopTipId, String content, Integer isSeriesSale, Integer shopCategory) {
        return listOfAgentId(agentId, typeId, shopTipId, content, false, null, isSeriesSale, shopCategory, false, false);
    }

    public static List<ShopInfo> listOfAgentId(Long agentId, Integer typeId, String content,
                                               Boolean checkRecommend,//是否检测是否推荐
                                               Boolean isRecommend//是否推荐（只有检测推荐时，此参数才有效）
    ) {
        return listOfAgentId(agentId, typeId, null, content, checkRecommend, isRecommend, null, ShopCategoryMan.shopTypeShopping, false, false);
    }

    public static List<ShopInfo> listOfAgentId(Long agentId, Integer typeId, String content,
                                               Boolean checkRecommend,//是否检测是否推荐
                                               Boolean isRecommend,//是否推荐（只有检测推荐时，此参数才有效）
                                               Boolean checkIsPreference,//是否检测是否优选
                                               Boolean isPreference //是否为优选（只有检测推荐时，此参数才有效）
    ) {
        return listOfAgentId(agentId, typeId, null, content, checkRecommend, isRecommend, null, ShopCategoryMan.shopTypeShopping, checkIsPreference, isPreference);
    }

    public static List<ShopInfo> listOfAgentId(Long agentId,
                                               Integer typeId,
                                               Long shopTipId, String content,
                                               Boolean checkRecommend,//是否检测是否推荐
                                               Boolean isRecommend,//是否推荐（只有检测推荐时，此参数才有效）
                                               Integer isSeriesSale,//是否批发商
                                               Integer shopCategory,//是否团购商家  SHOP_GROUP_TYPE// 0普通商家 1团购商家 2既是团购又是普通
//                                               Integer isGroupShop,//是否团购商家  SHOP_GROUP_TYPE// 0普通商家 1团购商家 2既是团购又是普通
                                               Boolean checkIsPreference,//是否检测是否优选
                                               Boolean isPreference //是否为优选（只有检测推荐时，此参数才有效）
    ) {
        List<Long> shopIds = ShopAgentRelationMemory.getInstance().listOfAgentId(agentId);
        List<ShopInfo> list = null;
        if (ValidateUtil.isAbsList(shopIds)) {
            list = new ArrayList<>();
            for (int i = 0; i < shopIds.size(); i++) {
                if (ValidateUtil.isNotID(shopIds.get(i))) {
                    continue;
                }

                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopIds.get(i));
                if (null == shopInfo) {
                    continue;
                }
                // 检测是不是所属代理 若不是  则不返回
                if (!checkShopBeLong(shopInfo, agentId)) {
                    continue;
                }

                //是否为批发商
                if (null != shopInfo.getIsSeriesSale() && null != isSeriesSale && 0 != isSeriesSale - shopInfo.getIsSeriesSale()) {
                    continue;
                }

                if (shopCategory == null) {
                    shopCategory = ShopCategoryMan.shopTypeShopping;
                }
//                // 剔除创业商圈的商家
                if (shopInfo.getCloudShopType() != null && (shopInfo.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_SQUARE) > 0) {
                    continue;
                }
                if (shopInfo.getShopCategory() != null && !ShopCategoryMan.validShopType(shopCategory, shopInfo.getShopCategory())) {
                    continue;
                }
                if (SYS_SETTINGS.DISTINGUISH_SHOP_RECOMMEND == 1 && shopCategory != null && shopCategory - ShopCategoryMan.shopTypeGroup == 0) {
                    // 团购商家推荐分类
                    if (checkRecommend && null != isRecommend && isRecommend) {
                        if (0 != 1 - shopInfo.getIsRecommend2()) {
                            continue;
                        }
                    }
                } else {
                    // 是否推荐店铺
                    if (checkRecommend && null != isRecommend && isRecommend) {
                        if (0 != 1 - shopInfo.getIsRecommend()) {
                            continue;
                        }
                    }
                }
                // // 是否推荐店铺
                // if (checkRecommend && null != isRecommend && isRecommend) {
                //     if (0 != 1 - shopInfo.getIsRecommend()) {
                //         continue;
                //     }
                // }
                // 是否是优选商家
                if (SYS_SETTINGS.DISTINGUISH_SHOP_RECOMMEND == 1 && shopCategory != null && shopCategory - ShopCategoryMan.shopTypeGroup == 0) {
                    // 团购商家优选
                    if (checkIsPreference && null != isPreference && isPreference) {
                        if (0 != 1 - shopInfo.getIsPreference2()) {
                            continue;
                        }
                    }
                } else {
                    // 优选商家
                    if (checkIsPreference && null != isPreference && isPreference) {
                        if (0 != 1 - shopInfo.getIsPreference()) {
                            continue;
                        }
                    }
                }
//                if (checkIsPreference && null != isPreference && isPreference) {
//                    if (0 != 1 - shopInfo.getIsPreference()) {
//                        continue;
//                    }
//                }
                // 店铺行业
                if (null != typeId) {   // 需要判断typeId
                    List<Integer> typeIdList = ShopTypeRelationMemory.getInstance().shopTypeList(shopInfo.getId());
                    boolean flag = false;
                    for (int j = 0; j < typeIdList.size(); j++) {
                        if (null == typeIdList.get(j)) {
                            continue;
                        }
                        if (0 == typeId - typeIdList.get(j)) {
                            flag = true;
                        }
                    }
                    if (!flag) {
                        continue;
                    }
                }

                //判断店铺是否有该标签
                if (ValidateUtil.isID(shopTipId) && !ShopTipRelationMemory.getInstance().shopHasTipId(shopInfo.getId(), shopTipId)) {
                    continue;
                }

                if (ValidateUtil.isNotNull(content) &&
                        !(SysCommon.hasKeyword(shopInfo.getShopName(), content)
                                || SysCommon.hasKeyword(shopInfo.getAffiche(), content)
                                || SysCommon.hasKeyword(shopInfo.getRegion(), content)
                                || SysCommon.hasKeyword(shopInfo.getDescs(), content))) {//如果需要判断搜索，搜索内容不包含
                    continue;
                }

                list.add(shopInfo);
            }
        }

        return list;
    }

    private static boolean checkShopBeLong(ShopInfo shopInfo, Long agentId) {
        if (shopInfo == null) {
            return true;
        }
        if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT != 1) {
            return true;
        }
        if (ValidateUtil.isNull(shopInfo.getCityAdmin())) {
            return true;
        }
        if (agentId == null) {
            return true;
        }
        List<String> tempList = UserAgentRelationMemory.getInstance().usernameListOfAgentId(agentId);
        if (tempList == null || tempList.size() == 0) {
            return true;
        }
        if (!shopInfo.getCityAdmin().equals(tempList.get(0))) {
            return false;
        }
        return true;
    }

    //获取店铺对应的商圈
    public static List<RegionInfoVO> getRegionListOfShop(Long shopId) {
        if (ValidateUtil.isNotID(shopId)) {
            return null;
        }
        List<ShopRegionRelation> relationList = ShopRegionRelationMemory.getInstance().listOfShopId(shopId);
        if (ValidateUtil.isAbsList(relationList)) {
            List<RegionInfoVO> regionInfoVOs = new ArrayList<RegionInfoVO>();
            for (int i = 0; i < relationList.size(); i++) {
                if (null == relationList.get(i)) {
                    continue;
                }
                RegionInfo regionInfo = RegionInfoMemory.getInstance().get(relationList.get(i).getRegionId());
                if (null == regionInfo) {
                    continue;
                }
                RegionInfoVO regionInfoVO = new RegionInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(regionInfo, regionInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                regionInfoVOs.add(regionInfoVO);
            }
            if (ValidateUtil.isAbsList(regionInfoVOs)) {
                return regionInfoVOs;
            }
        }
        return null;
    }


    //商户订单量增加
    public static ResultInfo addShopOrderCounts(Long shopId, String ownUsername, String username) {
        if (ValidateUtil.isNotID(shopId)) {
            return new ResultInfo("店铺不能为空");
        }

        //是否有该店铺的额外信息
        ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopId);
        if (null == shopInfoExtra) {  //没有新增
            //添加店铺额外信息
            addShopExtraInfo(shopId, ownUsername, username, 1, null);
        } else {//有，更新
            Integer monthCount = shopInfoExtra.getMonthOrderCount();
            Long lastTime = shopInfoExtra.getLastUpdateCountTime();
            if (ValidateUtil.isNotAbsInteger(monthCount)) {
                monthCount = 1;
            }
            if (ValidateUtil.isAbsLong(lastTime)) {
                if (DateUtils.isNowMonth(lastTime)) {//是当前月的数据直接更新
                    monthCount += 1;
                } else {//不是当前月 重置
                    monthCount = 1;
                }
            } else {
                monthCount = 1;
            }


            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.SHOP_INFO_EXTRA).append(" set orderCounts = ifNull(orderCounts,0)+1,monthOrderCount=").append(monthCount)
                    .append(",lastUpdateCountTime=").append(DateUtils.getCurrTime()).append(",updateUser = '")
                    .append(username).append("' where delFlag = 0 and shopId = ").append(shopId);
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("更新订单量失败:" + e.getMessage());
                return new ResultInfo("更新订单量失败，请稍后再试");
            }
            //缓存中新增
            ShopExtraInfoMemory.getInstance().addOrModify(shopId);
        }

        return new ResultInfo();
    }

    //商户订单量减少
    public static ResultInfo reduceShopOrderCounts(Long shopId, String ownUsername, String username) {
        if (ValidateUtil.isNotID(shopId)) {
            return new ResultInfo("店铺不能为空");
        }

        //是否有该店铺的额外信息
        ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopId);
        if (null == shopInfoExtra) {  //没有新增
            //添加店铺额外信息
            addShopExtraInfo(shopId, ownUsername, username, 0, null);
        } else {//有，更新
            Integer monthCount = shopInfoExtra.getMonthOrderCount();
            Long lastTime = shopInfoExtra.getLastUpdateCountTime();
            if (ValidateUtil.isNotAbsInteger(monthCount)) {
                monthCount = 0;
            }
            if (ValidateUtil.isAbsLong(lastTime)) {
                if (DateUtils.isNowMonth(lastTime)) {//是当前月的数据直接更新
                    monthCount -= 1;
                } else {//不是当前月 重置
                    monthCount = 0;
                }
            } else {
                monthCount = 0;
            }


            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.SHOP_INFO_EXTRA).append(" set orderCounts = ifNull(orderCounts,1)-1,monthOrderCount=").append(monthCount)
                    .append(",lastUpdateCountTime=").append(DateUtils.getCurrTime()).append(",updateUser = '")
                    .append(username).append("' where delFlag = 0 and shopId = ").append(shopId);
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("更新订单量失败:" + e.getMessage());
                return new ResultInfo("更新订单量失败，请稍后再试");
            }
            //缓存中新增
            ShopExtraInfoMemory.getInstance().addOrModify(shopId);
        }

        return new ResultInfo();
    }

    //添加对店铺的评分
    public static ResultInfo addShopScore(Long shopId, String ownUsername, String username, Integer star) {
        if (ValidateUtil.isNotID(shopId)) {
            return new ResultInfo("店铺不能为空");
        }
        if (null == star || star < 0) {
            return new ResultInfo("星级为空，不予以更改");
        }
        Long counts = 0L;
        StringBuilder countSql = new StringBuilder();
        countSql.append(" select count(1) as counts from ").append(PojoTables.ShopComment).append(" where shopId = ").append(shopId).append(" and delFlag = 0");
        try {
            counts = UserDaoSql.getInstance().getCount(countSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            counts = 0L;
        }
        if (counts == null) {
            counts = 0L;
        }
        //是否有该店铺的额外信息
        ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopId);
        if (null == shopInfoExtra) {  //没有新增
            //添加店铺额外信息
//            addShopExtraInfo(shopId, ownUsername, username, 1, Double.parseDouble(star + ""), star, Double.parseDouble(star + ""), 1);
            addShopExtraInfo(shopId, ownUsername, username, 1, Double.parseDouble(star + ""), star, Double.parseDouble(star + ""), 1, null, Integer.parseInt(counts.toString()));
        } else {//有，更新
            Integer totalScoreCount = shopInfoExtra.getTotalScoreCount() + 1;
            Double totalScore = shopInfoExtra.getTotalScore() + star;
            Integer shopStar = (int) (totalScore / totalScoreCount);
            Double shopScore = totalScore / totalScoreCount;

            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.SHOP_INFO_EXTRA).append(" set totalScoreCount = ").append(totalScoreCount).append(",totalScore=").append(totalScore)
                    .append(",star=").append(shopStar).append(",score=").append(shopScore);
            if (counts > 0) {
                sb.append(",totalCommentCount = ").append(counts);
            }
            sb.append(",updateUser = ")
                    .append(username).append(" where delFlag = 0 and shopId = ").append(shopId);
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("更新店铺评分失败:" + e.getMessage());
                return new ResultInfo("更新店铺评分失败，请稍后再试");
            }
            //缓存中修改
            ShopExtraInfoMemory.getInstance().addOrModify(shopId);
        }

        return new ResultInfo();
    }

    public static void addShopScore(Long shopId, String opUsername, List<ShopCommentInfo> list, Connection con) throws SQLException {
        if (list == null || list.isEmpty()) {
            return;
        }
        ShopInfo byId = ShopMemory.getInstance().getShopById(shopId);
        if (byId == null) {
            return;
        }
        Integer totalScoreCount = 0;
        Double totalScore = 0.0d;
        Integer orderCount = 0;
        for (ShopCommentInfo info : list) {
            if (info == null) {
                continue;
            }
            orderCount++;
            if (info.getStar() < 0) {
                continue;
            }
            totalScoreCount++;
            totalScore += info.getStar();
        }
        //是否有该店铺的额外信息
        ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopId);
        if (null == shopInfoExtra) {  //没有新增
            Integer shopStar = (int) (totalScore / totalScoreCount);
            Double shopScore = totalScore / totalScoreCount;
            //添加店铺额外信息
//            addShopExtraInfo(shopId, byId.getOwnUsername(), opUsername, orderCount, shopScore, shopStar, totalScore, totalScoreCount);
            addShopExtraInfo(shopId, byId.getOwnUsername(), opUsername, orderCount, shopScore, shopStar, totalScore, totalScoreCount, null, null);
        } else {//有，更新
            totalScoreCount += shopInfoExtra.getTotalScoreCount();
            totalScore = JYMathDoubleUtils.add(shopInfoExtra.getTotalScore(), totalScore);
            Integer shopStar = (int) (totalScore / totalScoreCount);
            Double shopScore = totalScore / totalScoreCount;

            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.SHOP_INFO_EXTRA).append(" set totalScoreCount = ").append(totalScoreCount).append(",totalScore=").append(totalScore)
                    .append(",star=").append(shopStar).append(",score=").append(shopScore).append(",updateUser = '")
                    .append(opUsername).append("' where delFlag = 0 and shopId = ").append(shopId);
            UserDaoSql.getInstance().executeBySql(sb.toString(), con);
        }
    }

    //添加商圈对应店铺关系
    public static void addAgentShopRelation(CityAgent cityAgent, Long shopId, String city, String opUsername) {
        if (ValidateUtil.isNotID(shopId)) {
            return;
        }
        if (null == cityAgent) {
            return;
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        //添加店铺与商圈的关系
        ShopAgentRelation shopAgentRelation = new ShopAgentRelation();
        shopAgentRelation.setShopId(shopId);
        shopAgentRelation.setShopOwnUsername(shopInfo.getOwnUsername());
        shopAgentRelation.setAgentId(cityAgent.getId());
        shopAgentRelation.setAgentUsername(cityAgent.getUsername());
        shopAgentRelation.setCity(city);
        shopAgentRelation.setDelFlag(0);
        shopAgentRelation.setCreateTime(DateUtils.getCurrTime());
        shopAgentRelation.setCreateUser(opUsername);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SHOP_AGENT_RELATION, shopAgentRelation);
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        }

        ShopAgentRelationMemory.getInstance().add(cityAgent.getId());
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_AGENT_RELATION_ADD).setLong01(cityAgent.getId());
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
    }


    //修改商圈对应店铺关系
    public static boolean modifyAgentShopRelation(CityAgent cityAgent, Long shopId, String opUsername) {
        if (ValidateUtil.isNotID(shopId)) {
            return false;
        }
        if (null == cityAgent) {
            return false;
        }
        Long agentId = ShopAgentRelationMemory.getInstance().getAgentByShopId(shopId);
        if (ValidateUtil.isNotID(agentId)) {//不存在 则添加
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
            //添加店铺与商圈的关系
            ShopAgentRelation shopAgentRelation = new ShopAgentRelation();
            shopAgentRelation.setShopId(shopId);
            shopAgentRelation.setShopOwnUsername(shopInfo.getOwnUsername());
            shopAgentRelation.setAgentId(cityAgent.getId());
            shopAgentRelation.setAgentUsername(cityAgent.getUsername());
            shopAgentRelation.setDelFlag(0);
            shopAgentRelation.setCreateTime(DateUtils.getCurrTime());
            shopAgentRelation.setCreateUser(opUsername);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.SHOP_AGENT_RELATION, shopAgentRelation);
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }

            ShopAgentRelationMemory.getInstance().add(cityAgent.getId());
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_AGENT_RELATION_ADD).setLong01(cityAgent.getId());
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        } else {//存在则修改
            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.SHOP_AGENT_RELATION).append(" set agentId = ").append(cityAgent.getId())
                    .append(", agentUsername = '").append(cityAgent.getUsername()).append("',updateUser = '").append(opUsername)
                    .append("' where delFlag =0 and agentId = ").append(agentId).append(" and shopId = ").append(shopId);
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
            ShopAgentRelationMemory.getInstance().delete(agentId, shopId);
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_AGENT_RELATION_DELETE).setLong01(agentId).setLong02(shopId);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
            ShopAgentRelationMemory.getInstance().add(cityAgent.getId());
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_AGENT_RELATION_ADD).setLong01(cityAgent.getId());
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }


        return true;
    }

    //修改店铺服务商圈  一个店铺对应多个商圈
    public static boolean modifyShopAgentsRelation(Long shopId, String agentIds, String opUsername) {
        if (ValidateUtil.isNotID(shopId) || ValidateUtil.isNull(agentIds)) {
            return false;
        }

        //删除之前的关联
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.SHOP_AGENT_RELATION).append(" set  delFlag = 1,updateUser = '").append(opUsername)
                .append("' where delFlag =0 and shopId = ").append(shopId);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        //添加新的关联
        String[] agentArr = agentIds.split(",");
        if (null != agentArr && agentArr.length > 0) {
            for (int i = 0; i < agentArr.length; i++) {
                if (ValidateUtil.isNull(agentArr[i])) {
                    continue;
                }
                Long agentId = Long.parseLong(agentArr[i]);
                if (ValidateUtil.isNotID(agentId)) {
                    continue;
                }

                CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
                if (null == cityAgent) {
                    continue;
                }
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
                //添加店铺与商圈的关系
                ShopAgentRelation shopAgentRelation = new ShopAgentRelation();
                shopAgentRelation.setShopId(shopId);
                shopAgentRelation.setShopOwnUsername(shopInfo.getOwnUsername());
                shopAgentRelation.setAgentId(agentId);
                shopAgentRelation.setAgentUsername(cityAgent.getUsername());
                shopAgentRelation.setDelFlag(0);
                shopAgentRelation.setCreateTime(DateUtils.getCurrTime());
                shopAgentRelation.setCreateUser(opUsername);
                try {
                    UserDaoSql.getInstance().insertObj(PojoTables.SHOP_AGENT_RELATION, shopAgentRelation);
                } catch (SQLException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }

        //更新缓存
        ShopAgentRelationMemory.getInstance().run();
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_AGENT_RELATION_RELOAD);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return true;
    }

    //-----------------------
    //添加店铺额外信息
    // private static ResultInfo addShopExtraInfo(Long shopId, String ownUsername, String username, Integer orderCounts) {
    //     return addShopExtraInfo(shopId, ownUsername, username, orderCounts, null);
    // }
    private static ResultInfo addShopExtraInfo(Long shopId, String ownUsername, String username, Integer orderCounts, Integer shopTag) {
        Integer star = 0;
        Double score = 0d;

        if (null != SYS_SETTINGS.SHOP_DEFAULT_STAR) {
            star = SYS_SETTINGS.SHOP_DEFAULT_STAR;
            score = Double.parseDouble(SYS_SETTINGS.SHOP_DEFAULT_STAR + "");
        }

        addShopExtraInfo(shopId, ownUsername, username, orderCounts, score, star, 0d, 0, shopTag, null);

        return new ResultInfo();
    }

    //添加店铺额外信息
//    private static ResultInfo addShopExtraInfo(Long shopId, String ownUsername, String username, Integer orderCounts, Double score, Integer star, Double totalScore, Integer totalScoreCount) {
    private static ResultInfo addShopExtraInfo(Long shopId, String ownUsername, String username, Integer orderCounts, Double score, Integer star, Double totalScore, Integer totalScoreCount, Integer shopTag, Integer commentCount) {
        Long time = DateUtils.getCurrTime();
        //添加店铺额外信息
        ShopInfoExtra extraInfo = new ShopInfoExtra();
        extraInfo.setShopId(shopId);//店铺ID
        extraInfo.setScore(score);//店铺的评分
        extraInfo.setStar(star);//店铺的星级评价
        extraInfo.setOwnUsername(ownUsername);//店主账号
        extraInfo.setCreateTime(time);
        extraInfo.setCreateUser(username);
        extraInfo.setDelFlag(0);
        extraInfo.setOrderCounts(orderCounts);//店铺订单总量
        extraInfo.setMonthOrderCount(orderCounts);//店铺当前月订单总量
        extraInfo.setTotalScore(totalScore);//店铺获取的评价总分
        extraInfo.setTotalScoreCount(totalScoreCount);//店铺获取的评价总个数
        extraInfo.setLastUpdateCountTime(time);//店铺获取的评价总个数
        extraInfo.setShopTag(shopTag == null ? 0 : shopTag);//
        extraInfo.setTotalCommentCount(commentCount == null ? 0 : commentCount);//
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SHOP_INFO_EXTRA, extraInfo);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("新增店铺时，添加店铺额外新出错:" + e.getMessage());
        }

        //缓存中新增
        ShopExtraInfoMemory.getInstance().addOrModify(shopId);
        return new ResultInfo();
    }

    //添加店铺额外信息(资质图片)
//    public static ResultInfo addShopExtraInfo(Long shopId, String ownUsername, String imageUrl2, String imageUrl4, String imageUrl5, String opUsername) {
    public static ResultInfo addShopExtraInfo(Long shopId, String ownUsername,
                                              String imageUrl2, // 店内环境
                                              String imageUrl4, // 营业执照
                                              String imageUrl5, // 法人手持身份证照
                                              String imageUrl6, // 身份证正面照
                                              String imageUrl7, // 身份证反面照
                                              String imageUrl8, // 合同照
                                              String imageUrl9, // 卫生许可照
                                              String imageUrl10, // 健康证
                                              String imageUrl11, // 食品经营许可证
                                              String imageUrl12, // 门脸照
                                              String imageUrl13, // 酒牌
                                              String opUsername) {
        Long time = DateUtils.getCurrTime();
        //添加店铺额外信息
        ShopInfoExtra extraInfo = new ShopInfoExtra();
        extraInfo.setShopId(shopId);//店铺ID
        extraInfo.setOwnUsername(ownUsername);//店主账号
        extraInfo.setCreateTime(time);
        extraInfo.setCreateUser(opUsername);
        extraInfo.setInstoreImageUrl(imageUrl2); // 店内环境
        extraInfo.setBuzzLicImageUrl(imageUrl4); // 营业执照
        extraInfo.setIDCardHImageUrl(imageUrl5); // 法人手持身份证照
        extraInfo.setIDCardAImageUrl(imageUrl6);  // 法人身份证照 正面
        extraInfo.setIDCardBImageUrl(imageUrl7); // 法人身份证照 反面
        extraInfo.setContractImageUrl(imageUrl8);// 合同照
        extraInfo.setHealthLicImageUrl(imageUrl9); // 卫生许可照
        extraInfo.setHealthCertImageUrl(imageUrl10); // 健康证照
        extraInfo.setFoodLicImageUrl(imageUrl11); // 食品经营许可证
        extraInfo.setShopFrontImageUrl(imageUrl12); // 门脸照
        extraInfo.setLiquorLicenseImageUrl(imageUrl13); // 酒牌

        extraInfo.setDelFlag(0);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SHOP_INFO_EXTRA, extraInfo);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("新增店铺时，添加店铺额外新出错:" + e.getMessage());
        }
        //缓存中新增
        ShopExtraInfoMemory.getInstance().addOrModify(shopId);
        return new ResultInfo();
    }

    public static void addShopExtraInfo(ShopInfoExtra extra, Connection cn) throws Exception {
        if (extra == null) {
            throw new Exception("信息不能为空");
        }
        if (cn == null) {
            UserDaoSql.getInstance().saveObj(PojoTables.SHOP_INFO_EXTRA, extra);
            ShopExtraInfoMemory.getInstance().addOrModify(extra.getShopId());
        } else {
            UserDaoSql.getInstance().saveObj(PojoTables.SHOP_INFO_EXTRA, extra, cn);
        }
    }
//    //删除店铺关联的行业
//    private static ResultInfo deleteShopTypes(String shopIds) {
//        if (ValidateUtil.isNull(shopIds)) {
//            return new ResultInfo();
//        }
//        StringBuilder sbType = new StringBuilder();
//        sbType.append("delete from ").append(PojoTables.ShopTypeRelation).append(" where shopId in ( ").append(shopIds).append(")");
//        try {
//            UserDaoSql.getInstance().executeBySql(sbType.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return new ResultInfo("删除店铺失败了，请稍后再试");
//        }
//        return new ResultInfo();
//    }

    // public static ResultInfo deleteShopTypes(String shopIds, String opUsername) {
    //     return deleteShopTypes(shopIds, null, opUsername);
    // }

    //删除店铺关联的行业
    public static ResultInfo deleteShopTypes(String shopIds, String[] shopIdArr, String opUsername) {
        if (ValidateUtil.isNull(shopIds)) {
            return new ResultInfo();
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.ShopTypeRelation).append(" set delFlag = 1,updateUser='").append(opUsername).append("' where shopId in (").append(shopIds).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("删除店铺所属行业失败，请稍后再试");
        }

        if (null != shopIdArr && shopIdArr.length > 0) {
            // 删除缓存
            for (int i = 0; i < shopIdArr.length; i++) {
                String idStr = shopIdArr[i];
                if (ValidateUtil.isNull(idStr)) {
                    continue;
                }

                try {
                    ShopTypeRelationMemory.getInstance().delete(Long.parseLong(idStr));
                    try {
                        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_TYPE_RELATION_DEL).setLong01(Long.parseLong(idStr));
                        JmsSender.setTopicSender(notify);
                    } catch (Exception e) {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return new ResultInfo();
    }



    // 根据商圈获取商圈下的商家id
    public static Set<Long> listOfShopIdByCityAgentId(Set<Long> cityAgentSet) {
        if (cityAgentSet == null || cityAgentSet.isEmpty()) {
            return null;
        }
        Set<Long> shopIdSet = new HashSet<>();
        for (Long id : cityAgentSet) {
            List<Long> tempSet = ShopAgentRelationMemory.getInstance().listOfAgentId(id);
            if (tempSet != null && !tempSet.isEmpty()) {
                for (Long shopId : tempSet) {
                    shopIdSet.add(shopId);
                }
            }
        }
        return shopIdSet;
    }


    // 同步店铺信息 ----------------------------------------------------
    public static void batchShopSynch(ShopInfo baseShopInfo, String shopIds, String opUsername, boolean isSynchAffiche, boolean isSynchDelivery, boolean isSynchDescs, boolean isSynchOpen) throws Exception {
        if (baseShopInfo == null) {
            throw new Exception("基础同步店铺信息不能为空");
        }
        if (StringUtils.isEmpty(shopIds)) {
            throw new Exception("需要同步的店铺信息不能为空");
        }
        String[] split = StringUtils.split(shopIds, ",");
        if (split.length == 0) {
            return;
        }
        HashSet<Long> shopIdSet = new HashSet<>();
        for (String lTStr : split) {
            try {
                Long shopId = Long.parseLong(lTStr);
                shopIdSet.add(shopId);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        // 去除本身的
        shopIdSet.remove(baseShopInfo.getId());
        if (shopIdSet.isEmpty()) {
            return;
        }
        // 同步店铺信息
        synchShop(baseShopInfo, shopIdSet, opUsername, isSynchAffiche, isSynchDelivery, isSynchDescs, isSynchOpen);
    }

    // 同步店铺的公告信息
    public static void synchShop(ShopInfo baseShopInfo, HashSet<Long> shopIds, String opUsername, boolean isSynchAffiche, boolean isSynchDelivery, boolean isSynchDescs, boolean isSynchOpen) throws Exception {
        // 开始同步信息
        Connection conn = UserDaoSql.getInstance().getConnection();
        conn.setAutoCommit(false);
        StringBuilder updateSql = new StringBuilder();
        updateSql.append("update ").append(PojoTables.ShopInfo)
                .append(" set ").append(" updateUser ='").append(opUsername).append("'");
        // 1.同步店铺公告信息
        if (isSynchAffiche) {
            if (baseShopInfo.getAffiche() == null) {
                updateSql.append(",affiche = ").append("null");
            } else {
                updateSql.append(",affiche = '").append(baseShopInfo.getAffiche()).append("'");
            }
            // 多语言的问题
            if (baseShopInfo.getAfficheLang() == null) {
                updateSql.append(",afficheLang = ").append("null");
            } else {
                updateSql.append(",afficheLang = '").append(baseShopInfo.getAfficheLang()).append("'");
            }
        }
        // 2. 同步店铺配送费信息
        if (isSynchDelivery) {
            // 起送费  运费 freeYunFei freeYunFeiMoney freeYunfeiShop
            // startFree
            if (baseShopInfo.getStartFree() == null) {
                updateSql.append(",startFree = ").append("null");
            } else {
                updateSql.append(",startFree = ").append(baseShopInfo.getStartFree()).append("");
            }
            // yunfei
            if (baseShopInfo.getYunfei() == null) {
                updateSql.append(",yunFei = ").append("null");
            } else {
                updateSql.append(",yunFei = ").append(baseShopInfo.getYunfei());
            }
            // freeYunFei
            if (baseShopInfo.getFreeYunFei() == null) {
                updateSql.append(",freeYunFei = ").append("null");
            } else {
                updateSql.append(",freeYunFei = ").append(baseShopInfo.getFreeYunFei());
            }
            // freeYunFeiMoney
            if (baseShopInfo.getFreeYunFeiMoney() == null) {
                updateSql.append(",freeYunFeiMoney = ").append("null");
            } else {
                updateSql.append(",freeYunFeiMoney = ").append(baseShopInfo.getFreeYunFeiMoney());
            }
            // freeYunfeiShop
            if (baseShopInfo.getFreeYunFeiShop() == null) {
                updateSql.append(",freeYunFeiShop = ").append("null");
            } else {
                updateSql.append(",freeYunFeiShop = ").append(baseShopInfo.getFreeYunFeiShop());
            }
            // 固定费用 fixedCost
            if (baseShopInfo.getFixedCost() == null) {
                updateSql.append(",fixedCost = ").append("null");
            } else {
                updateSql.append(",fixedCost = ").append(baseShopInfo.getFixedCost());
            }
            // 超出后onekmCost
            if (baseShopInfo.getOneKmCost() == null) {
                updateSql.append(",oneKmCost = ").append("null");
            } else {
                updateSql.append(",oneKmCost = ").append(baseShopInfo.getOneKmCost());
            }
            //withinDistance
            if (baseShopInfo.getWithinDistance() == null) {
                updateSql.append(",withinDistance = ").append("null");
            } else {
                updateSql.append(",oneKmCost = ").append(baseShopInfo.getWithinDistance());
            }
            // 配送设置
            updateSql.append(",isPeiSong = ").append(baseShopInfo.getIsPeiSong());
            // 自配送
            if (baseShopInfo.getIsSelfPost() == null) {
                updateSql.append(",isSelfPost = ").append("null");
            } else {
                updateSql.append(",isSelfPost = ").append(baseShopInfo.getIsSelfPost());
            }
            // 自取IsDaoDian
            updateSql.append(",isDaoDian = ").append(baseShopInfo.getIsDaoDian());
        }
        // 3. 描述信息
        if (isSynchDescs) {
            // 描述
            if (baseShopInfo.getDescs() == null) {
                updateSql.append(",descs = ").append("null");
            } else {
                updateSql.append(",descs = '").append(baseShopInfo.getDescs()).append("'");
            }
            // 多语言
            if (baseShopInfo.getDescsLang() == null) {
                updateSql.append(",descsLang = ").append("null");
            } else {
                updateSql.append(",descsLang = '").append(baseShopInfo.getDescsLang()).append("'");
            }
        }
        // 4. 营业设置
        if (isSynchOpen) {
            // 自动开关店？
            updateSql.append(",autoClose = ").append(baseShopInfo.getAutoClose());
            // 还有营业时间设置
            if (baseShopInfo.getWorktime() == null) {
                updateSql.append(",workTime = ").append("null");
            } else {
                updateSql.append(",workTime = '").append(baseShopInfo.getWorktime()).append("'");
            }
        }
        // where 条件语句
        updateSql.append(" where id in (").append(StringUtils.join(shopIds, ",")).append(") and delFlag = 0");
        UserDaoSql.getInstance().executeBySql(updateSql.toString(), conn);
        try {
            conn.commit();
        } catch (Exception e) {
            UserDaoSql.getInstance().rollback(conn);
            throw new Exception(e.getMessage());
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        // 缓存信息
        ShopMemory.getInstance().modify(StringUtils.join(shopIds, ","));
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFOS_UPDATE).setStr01(StringUtils.join(shopIds, ","));
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
    }

    // todo:店铺行业
    public static ResultInfo dealShopTypes(Long shopId, boolean isUpdate, String shopType, String opUser) {
        if (isUpdate) {
            ResultInfo typeResult = ShopMan.deleteShopTypes(shopId + "", null, opUser);
            if (null == typeResult) {
                return new ResultInfo("删除店铺行业时失败，请稍后再试");
            } else {
                if (!typeResult.isSuccess()) {
                    return typeResult;
                }
                // 删除店铺关联行业
                ShopTypeRelationMemory.getInstance().delete(shopId);    //
            }
        }
        //重新添加店铺行业关联
        if (ValidateUtil.isNotNull(shopType)) {
            Set<String> set = CommonUtils.splitToSet(shopType, String.class);
            String[] typs = shopType.split(",");
            if (null != set & set.size() > 0) {
                long time = DateUtils.getCurrTime();
                for (int i = 0; i < typs.length; i++) {
                    try {
                        ShopTypeRelation shopTypeRelation = new ShopTypeRelation();
                        shopTypeRelation.setShopId(shopId);
                        shopTypeRelation.setShopTypeId(Integer.parseInt(typs[i]));
                        shopTypeRelation.setCreateTime(time);
                        shopTypeRelation.setCreateUser(opUser);
                        shopTypeRelation.setDelFlag(0);
                        shopTypeRelation.setOrderNo(0);
                        try {
                            UserDaoSql.getInstance().insertObj(PojoTables.ShopTypeRelation, shopTypeRelation);
                        } catch (SQLException e) {
                            e.printStackTrace();
                            return new ResultInfo("店铺关联行业失败，请稍后再试");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                }
                ShopTypeRelationMemory.getInstance().add(shopId);
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_TYPE_RELATION_RELOAD).setLong01(shopId);
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            }
        }
        return new ResultInfo();
    }


    public static List<ShopTypeInfoVO> listShopTypeInfoVoByShopId(Long shopId) {
        if (ValidateUtil.isNotID(shopId)) {
            return Collections.emptyList();
        }
        //获取店铺所属行业
        List<ShopTypeInfoVO> typeInfoVOList = new ArrayList<ShopTypeInfoVO>();
        List<Integer> typeList = ShopTypeRelationMemory.getInstance().shopTypeList(shopId);

        if (ValidateUtil.isAbsList(typeList)) {
            ShopTypeInfoVO shopTypeInfoVO = null;
            for (int j = 0; j < typeList.size(); j++) {
                if (null == typeList.get(j)) {
                    continue;
                }

            }
            return typeInfoVOList;
        }
        return Collections.emptyList();
    }

    // todo : 修改
    public static ResultInfo shopModifyYunfei(ShopInfo shopInfo,
                                              Integer isPeiSong, Integer isDaoDian, Integer isSelfPost,
                                              Double yunfei,
                                              Double startFree,
                                              Double freeYunFei, Double freeYunFeiShop, Double freeYunFeiMoney,
                                              Double fixedCost, Double withinDistance, Double oneKmCost,
                                              Double fixedWeightCost, Double oneKgWeightCost, Double withinWeight,
                                              String opUser) {
        if (null == shopInfo) {
            return new ResultInfo("店铺信息不存在，请查证");
        }
        if (null == isPeiSong) {
            isPeiSong = shopInfo.getIsPeiSong();
        }
        if (null == isDaoDian) {
            isDaoDian = shopInfo.getIsDaoDian();
        }
        if (null == isSelfPost) {
            isSelfPost = shopInfo.getIsSelfPost();
        }
        if (null == yunfei) {
            yunfei = shopInfo.getYunfei();
        }
        if (null == fixedCost) {
            fixedCost = shopInfo.getFixedCost();
        } else if (fixedCost < 0) {
            return new ResultInfo("配送固定费用不能为负值");
        }
        if (null == withinDistance) {
            withinDistance = shopInfo.getWithinDistance();
        } else if (withinDistance < 0) {
            return new ResultInfo("指定配送距离不能为负值");
        }
        if (null == oneKmCost) {
            oneKmCost = shopInfo.getOneKmCost();
        } else if (oneKmCost < 0) {
            return new ResultInfo("超距离外单公里费用不能为负值");
        }

        if (null == fixedWeightCost) {
            fixedWeightCost = shopInfo.getFixedWeightCost();
        } else if (fixedWeightCost < 0) {
            return new ResultInfo("重量固定费不能为空");
        }
        if (null == oneKgWeightCost) {
            oneKgWeightCost = shopInfo.getOneKgWeightCost();
        } else if (oneKgWeightCost < 0) {
            return new ResultInfo("超出后的钱数不能为空");
        }
        if (null == withinWeight) {
            withinWeight = shopInfo.getWithinWeight();
        } else if (withinWeight < 0) {
            return new ResultInfo("固定重量不能为空");
        }
        //满足的商品金额（减运费）
        if (null == freeYunFei) {
            freeYunFei = shopInfo.getFreeYunFei();
        }
        //需要减的配送费金额（-1时为免配送费）
        if (null == freeYunFeiMoney) {
            freeYunFeiMoney = shopInfo.getFreeYunFeiMoney();
        }
        //减运费金额 商家承担部分
        if (null == freeYunFeiShop) {
            freeYunFeiShop = shopInfo.getFreeYunFeiShop();
        }

        if (null == startFree) {
            startFree = shopInfo.getStartFree();
        }
        //修改
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set ")
                .append("startFree=").append(startFree)
                .append(",freeYunFei=").append(freeYunFei).append(",freeYunFeiShop=").append(freeYunFeiShop).append(",freeYunFeiMoney=").append(freeYunFeiMoney)
                .append(",yunfei=").append(yunfei)
                .append(",fixedCost=").append(fixedCost).append(",withinDistance=").append(withinDistance).append(",oneKmCost=").append(oneKmCost)
                .append(",fixedWeightCost=").append(fixedWeightCost).append(",oneKgWeightCost=").append(oneKgWeightCost).append(",withinWeight=").append(withinWeight)
                .append(",isPeiSong=").append(isPeiSong).append(",isDaoDian=").append(isDaoDian).append(",isSelfPost=").append(isSelfPost)
                .append(",updateUser='").append(opUser).append("'").append(" where delFlag =0 and id = ").append(shopInfo.getId());

        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t" + sb.toString());
        //保存到数据库
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("修改失败，请稍后再试");
        }

        //修改店铺缓存
        ShopMemory.getInstance().modifyById(shopInfo.getId());
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopInfo.getId());
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return new ResultInfo();
    }


}
